import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import api from '@/api';

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null);
  const accessToken = ref(localStorage.getItem('accessToken') || null);
  
  const isAuthenticated = computed(() => !!user.value);
  const isAdmin = computed(() => user.value?.role === 'admin');
  
  /**
   * 登录
   */
  async function login(credentials) {
    try {
      const response = await api.post('/auth/login', credentials);
      const { user: userData, accessToken: token } = response.data.data;
      
      user.value = userData;
      accessToken.value = token;
      localStorage.setItem('accessToken', token);
      
      return userData;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 注册
   */
  async function register(userData) {
    try {
      const response = await api.post('/auth/register', userData);
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 登出
   */
  async function logout() {
    try {
      await api.post('/auth/logout');
    } catch (error) {
      // 忽略错误，继续登出
    } finally {
      user.value = null;
      accessToken.value = null;
      localStorage.removeItem('accessToken');
    }
  }
  
  /**
   * 获取当前用户信息
   */
  async function fetchCurrentUser() {
    try {
      const response = await api.get('/auth/me');
      user.value = response.data.data;
      return user.value;
    } catch (error) {
      user.value = null;
      accessToken.value = null;
      localStorage.removeItem('accessToken');
      throw error;
    }
  }
  
  /**
   * 刷新Token
   */
  async function refreshToken() {
    try {
      const response = await api.post('/auth/refresh');
      const { user: userData, accessToken: token } = response.data.data;
      
      user.value = userData;
      accessToken.value = token;
      localStorage.setItem('accessToken', token);
      
      return userData;
    } catch (error) {
      user.value = null;
      accessToken.value = null;
      localStorage.removeItem('accessToken');
      throw error;
    }
  }
  
  /**
   * 修改密码
   */
  async function changePassword(oldPassword, newPassword) {
    try {
      await api.put('/auth/password', { oldPassword, newPassword });
      // 修改密码后会登出所有设备，需要重新登录
      await logout();
    } catch (error) {
      throw error;
    }
  }
  
  return {
    user,
    accessToken,
    isAuthenticated,
    isAdmin,
    login,
    register,
    logout,
    fetchCurrentUser,
    refreshToken,
    changePassword,
  };
});


